﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Data;

namespace Mal.Balades.Admin.Converters
{
    public class ViewModelViewConverter : IValueConverter
    {
        #region Fields
        private static Dictionary<Type, Type> viewModelViewMapping;
        #endregion      

        #region Methods
        public static void Register(Type viewModel, Type view)
        {
            if (viewModelViewMapping == null)
                viewModelViewMapping = new Dictionary<Type, Type>();

            if (!viewModelViewMapping.ContainsKey(viewModel))
            {
                viewModelViewMapping.Add(viewModel, view);
            }
        }

        public static void UnregisterAll()
        {
            if (viewModelViewMapping != null)
            {
                viewModelViewMapping.Clear();
            }
        }

        public static void Unregister(Type viewModel)
        {
            if (viewModelViewMapping != null)
            {  
                if (viewModelViewMapping.ContainsKey(viewModel))
                {
                    viewModelViewMapping.Remove(viewModel);
                }
            }
        }

        public static UserControl GetControl(object viewModel)
        {
            if (viewModelViewMapping != null)
            {
                if (viewModelViewMapping.ContainsKey(viewModel.GetType()))
                {
                    UserControl view = (UserControl)Activator.CreateInstance(viewModelViewMapping[viewModel.GetType()]);
                    view.DataContext = viewModel;
                    return view;
                }
            }

            return null;
        }

        #endregion       

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            return GetControl(value);           
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
